package client.role;

import client.common.result.Result;
import client.common.vo.PermissionVO;
import remote.service.PermissionService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色详情窗口，展示角色对应的权限
 */
public class RoleDetailDialog extends JDialog {
    private PermissionService permissionService;
    private JTable permissionTable;
    private PermissionTableModel permissionTableModel;
    private List<PermissionVO> permissions; // 保存权限数据
    private List<Integer> permissionIds; // 保存当前选择的权限ID
    
    public RoleDetailDialog(int roleId) {
        setTitle("角色权限详情");
        setSize(800, 600);
        setLocationRelativeTo(null); // 居中
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        
        permissionService = new PermissionService() {
        };
        permissionTableModel = new PermissionTableModel();
        
        initUI(roleId);
        loadPermissions(roleId); // 加载角色对应的权限
    }
    
    /**
     * 初始化界面组件
     */
    private void initUI(int roleId) {
        JPanel mainPanel = new JPanel(new BorderLayout());
        
        permissionTable = new JTable(permissionTableModel) {
            @Override
            public Class getColumnClass(int column) {
                if (column == 0) {
                    return Boolean.class;
                }
                return String.class;
            }
        };
        
        permissionTable.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(permissionTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        
        // 添加提示信息
        JLabel hintLabel = new JLabel("对原勾选权限功能取消勾选即删除权限；勾选新权限即添加权限，点击提交完成修改");
        hintLabel.setHorizontalAlignment(SwingConstants.CENTER);
        mainPanel.add(hintLabel, BorderLayout.NORTH);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        
        JButton submitButton = new JButton("提交");
        submitButton.setPreferredSize(new Dimension(150, 40)); // 放大提交按钮
        submitButton.addActionListener(e -> submitPermissions(roleId));
        buttonPanel.add(submitButton);
        
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dispose());
        buttonPanel.add(closeButton);
        
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
    }
    
    /**
     * 加载角色的权限列表
     */
    private void loadPermissions(int roleId) {
        SwingWorker<Result<List<PermissionVO>>, Void> worker = new SwingWorker<Result<List<PermissionVO>>, Void>() {
            @Override
            protected Result<List<PermissionVO>> doInBackground() throws Exception {
                return permissionService.getPermissionListByRole(roleId);
            }
            
            @Override
            protected void done() {
                try {
                    Result<List<PermissionVO>> result = get();
                    if (result.getCode() == 200) {
                        permissions = result.getData();
                        permissionTableModel.setPermissions(permissions);
                        permissionIds = permissions.stream().filter(PermissionVO::getSelected).map(PermissionVO::getId).collect(Collectors.toList());
                    } else {
                        JOptionPane.showMessageDialog(RoleDetailDialog.this, "加载权限失败: " + result.getMessage());
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(RoleDetailDialog.this, "加载权限时发生错误: " + e.getMessage());
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 提交权限修改
     */
    private void submitPermissions(Integer roleId) {
        List<String> addPermissionList = new ArrayList<>();
        List<String> delPermissionList = new ArrayList<>();
        // 遍历权限列表，收集当前选择的权限ID
        for (PermissionVO permission : permissions) {
            if (permission.getSelected() && !permissionIds.contains(permission.getId())) {
                addPermissionList.add(permission.getId().toString());
            } else if (!permission.getSelected() && permissionIds.contains(permission.getId())) {
                delPermissionList.add(permission.getId().toString());
            }
        }
        
        String addPermissionStr = String.join(",", addPermissionList);
        String delPermissionStr = String.join(",", delPermissionList);
        
        // 调用修改接口
        Result result = permissionService.alterPermissionFormRole(roleId, addPermissionStr, delPermissionStr);
        if (result.getCode() == 200) {
            JOptionPane.showMessageDialog(this, "权限修改成功");
        } else {
            JOptionPane.showMessageDialog(this, "权限修改失败: " + result.getMessage());
        }
    }
    
    /**
     * 权限表格模型
     */
    class PermissionTableModel extends AbstractTableModel {
        
        private final String[] columnNames = {"选择", "ID", "描述"};
        private List<PermissionVO> permissions;
        
        public void setPermissions(List<PermissionVO> permissions) {
            this.permissions = permissions;
            fireTableDataChanged();
        }
        
        @Override
        public int getRowCount() {
            return permissions == null ? 0 : permissions.size();
        }
        
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 0) {
                return Boolean.class;
            } else if (columnIndex == 1) {
                return Integer.class;
            }
            return String.class;
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex == 0; // 仅复选框列可编辑
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (permissions == null || rowIndex >= permissions.size()) {
                return null;
            }
            PermissionVO permission = permissions.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return permission.getSelected(); // 是否选中
                case 1:
                    return permission.getId(); // 权限ID
                case 2:
                    return permission.getDescription(); // 权限描述
                default:
                    return null;
            }
        }
        
        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if (permissions == null || rowIndex >= permissions.size()) {
                return;
            }
            PermissionVO permission = permissions.get(rowIndex);
            if (columnIndex == 0 && aValue instanceof Boolean) {
                permission.setSelected((Boolean) aValue);
                fireTableCellUpdated(rowIndex, columnIndex);
            }
        }
    }
}
